package com.mashrabenaab;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Vector;
import org.apache.http.util.ByteArrayBuffer;
import com.mashrabenaab.adapter.MnAdapterLive;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

public class LiveListActivity extends ListActivity {
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mn_list_live);
		if (isValidate()) {
			new ParseXmlTaskGetList().execute();
		}
	}

	public static String[] splitString(String original, String separator) {
		Vector nodes = new Vector();
		int index = original.indexOf(separator);
		while (index >= 0) {
			nodes.addElement(original.substring(0, index));
			original = original.substring(index + separator.length());
			index = original.indexOf(separator);
		}
		nodes.addElement(original);
		String[] result = new String[nodes.size()];
		if (nodes.size() > 0) {
			for (int loop = 0; loop < nodes.size(); loop++) {
				result[loop] = (String) nodes.elementAt(loop);
			}
		}
		return result;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Magazine magazine = (Magazine) l.getItemAtPosition(position);
		
		if (isValidate()) {
			new AsynchTaskDownload().execute(magazine);
		}
		//downloadMagazine(magazine);

		/*
		 * int countFile = Integer.parseInt(magazine.getPagecount());
		 * GlobalService.createLocalDirIfNotExists(magazine); for (int x = 1; x
		 * <= countFile; x++) { DownloadFromUrl(
		 * GlobalService.getFolderNameLive(magazine, getBaseContext()) +
		 * Integer.toString(x) + ".gif",
		 * GlobalService.getFolderNameLocal(magazine) + "/" +
		 * Integer.toString(x) + ".gif"); } Context context =
		 * getApplicationContext(); CharSequence text = "Done"; int duration =
		 * Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, text,
		 * duration); toast.show();
		 */

	}

	private void downloadMagazine(Magazine magazine) {
		int countFile = Integer.parseInt(magazine.getPagecount());
		GlobalService.createLocalDirIfNotExists(magazine);
		for (int x = 0; x <= countFile; x++) {
			downloadFromUrl(
					GlobalService.getFolderNameLive(magazine, getBaseContext())
							+ Integer.toString(x) + ".gif",
					GlobalService.getFolderNameLocal(magazine) + "/"
							+ Integer.toString(x) + ".gif");
			
		}		
	}
	
	private void writeToTextFile(Magazine magazine){
		
	}

	private void downloadFromUrl(String imageURL, String fileName) {
		try {
			URL url = new URL(imageURL);
			File file = new File(Environment.getExternalStorageDirectory(),
					fileName);
			// File file = new File(fileName);

			long startTime = System.currentTimeMillis();
			Log.d("ImageManager", "download begining");
			Log.d("ImageManager", "download url:" + url);
			Log.d("ImageManager", "downloaded file name:" + fileName);
			/* Open a connection to that URL. */
			URLConnection ucon = url.openConnection();

			InputStream is = ucon.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);

			ByteArrayBuffer baf = new ByteArrayBuffer(50);
			int current = 0;
			while ((current = bis.read()) != -1) {
				baf.append((byte) current);
			}

			/* Convert the Bytes read to a String. */
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(baf.toByteArray());
			fos.close();

		} catch (IOException e) {
			Log.d("ImageManager", "Error: " + e);
		}

	}

	private boolean isValidate() {
		if (!GlobalService.isOnline(this)) {
			GlobalService
					.MessageBox("Not or limited internet connection", this);
			return false;
		}
		return true;
	}

	private ArrayList<Magazine> processServiceGetList() {
		ArrayList<Magazine> theArrayList = new ArrayList<Magazine>();
		try {

			URL url = new URL(getString(R.string.url_base) + "info.txt");

			BufferedReader in = new BufferedReader(new InputStreamReader(
					url.openStream()));
			String strLine;
			while ((strLine = in.readLine()) != null) {
				Magazine magazine = new Magazine();
				String[] strArr = splitString(strLine, "-");
				magazine.setEdition(strArr[0]);
				magazine.setMonthName(strArr[1]);
				magazine.setYearName(strArr[2]);
				magazine.setPagecount(strArr[3]);
				String imageUrl = GlobalService.getFolderNameLive(magazine,
						this) + "0.gif";
				magazine.setImageUrl(imageUrl);
				theArrayList.add(magazine);

			}
			in.close();
		} catch (MalformedURLException e) {
			Log.e("MalformedURLException is : ", e.toString());
		} catch (IOException e) {
			Log.e("IOException is : ", e.toString());
		}
		return theArrayList;
	}

	class ParseXmlTaskGetList extends
			AsyncTask<Void, Void, ArrayList<Magazine>> {
		private final ProgressDialog dialog = new ProgressDialog(
				LiveListActivity.this);

		protected void onPreExecute() {
			this.dialog.setMessage("Getting editions list...");
			this.dialog.show();
		}

		protected ArrayList<Magazine> doInBackground(Void... unused) {
			return processServiceGetList();
		}

		protected void onPostExecute(ArrayList<Magazine> cclist) {
			if (this.dialog.isShowing())
				this.dialog.dismiss();
			if (cclist != null) {
				MnAdapterLive m_adapter = new MnAdapterLive(
						LiveListActivity.this, cclist);
				setListAdapter(m_adapter);
				// flagInitiated++;
			}
		}
	}

	class AsynchTaskDownload extends
			AsyncTask<Object, Void, Void> {
		private final ProgressDialog dialog = new ProgressDialog(
				LiveListActivity.this);

		protected void onPreExecute() {
			this.dialog.setMessage("Downloading...");
			this.dialog.show();
		}

		  protected void onProgressUpdate(Integer... values) {
		   // TODO Auto-generated method stub
		  // progressBar.setProgress(values[0]);
		  }
		
		protected Void doInBackground(Object... params) {
			Magazine magazine = (Magazine)params[0];
			downloadMagazine(magazine);
			return null;
			//return processServiceGetList();
		}

		protected void onPostExecute(Void result) {
			if (this.dialog.isShowing())
				this.dialog.dismiss();
			/*if (cclist != null) {
				MnAdapterLive m_adapter = new MnAdapterLive(
						LiveListActivity.this, cclist);
				setListAdapter(m_adapter);
				// flagInitiated++;
			}*/
		}
	}

}